/**
 * 余额记录明细
 * author wim
 */
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/address_entity.dart';
import 'package:panda/entity/common_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';
import '../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class ScoreRecordPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ScoreRecordView();
  }
}

class ScoreRecordView extends State<ScoreRecordPage> {
  List<CommonEntityDataData> dataList = new List();
  int page = 1;
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();
  String time1 = "全部日期", time2 = "全部日期";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    var today = DateTime.now();
    // time1 = DateUtils.instance.getFormartData(
    //     timeSamp: today.millisecondsSinceEpoch, format: "yyyy-MM-dd");
    // time2 = time1;
    setState(() {});
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page;
    map['per'] = 10;
    if (!time1.contains("全部")) {
      map['start'] = time1;
      map['end'] = time2;
    }
    map['sign_type'] = SignType.SCORE_RECORD;
    Response<String> response =
        await HttpUtil().post(Api.SCORE_RECORD, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    CommonEntityEntity homeListEntity =
        new CommonEntityEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          _controller.finishRefresh();
          _controller.resetLoadState();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
          _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text('积分明细',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
          color: white,
          child: Column(children: <Widget>[
            Container(
                padding: EdgeInsets.fromLTRB(20,10,20,10),
                child: Row(children: <Widget>[
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(20, 3, 10, 3),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(3)),
                      child: Row(children: <Widget>[
                        Text('$time1',
                            style: TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                        Icon(
                          Icons.arrow_drop_down,
                          color: mainColor,
                        )
                      ]),
                    ),
                    onTap: () {
                      DatePicker.showDatePicker(context,
                          showTitleActions: true,
                          onChanged: (date) {}, onConfirm: (date) {
                        setState(() {
                          time1 = DateUtils.instance.getFormartData(
                              timeSamp: date.millisecondsSinceEpoch,
                              format: "yyyy-MM-dd");
                        });
                      }, currentTime: DateTime.now(), locale: LocaleType.zh);
                    },
                  ),
                  Expanded(
                    child: Center(
                        child: Text('至',
                            style: TextStyle(
                                color: black,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)))),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(20, 3, 10, 3),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(3)),
                      child: Row(children: <Widget>[
                        Text('$time2',
                            style: TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                        Icon(
                          Icons.arrow_drop_down,
                          color: mainColor,
                        )
                      ]),
                    ),
                    onTap: () {
                      DatePicker.showDatePicker(context,
                          showTitleActions: true,
                          onChanged: (date) {}, onConfirm: (date) {
                        setState(() {
                          time2 = DateUtils.instance.getFormartData(
                              timeSamp: date.millisecondsSinceEpoch,
                              format: "yyyy-MM-dd");
                        });
                      }, currentTime: DateTime.now(), locale: LocaleType.zh);
                    },
                  ),
                  Container(
                    width: 20,
                  ),
                  GestureDetector(
                      child: Container(
                        padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                        decoration: BoxDecoration(
                            border: Border.all(color: mainColor, width: 1),
                            borderRadius: BorderRadius.circular(3)),
                        child: Row(children: <Widget>[
                          Text('搜索',
                              style: TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE))),
                        ]),
                      ),
                      onTap: () {
                        page = 1;
                        loadList();
                      })
                ])),
            Container(height: 1, width: double.infinity, color: divideColor),
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: ListView.separated(
                  itemBuilder: _renderRow,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      color: divideColor,
                      height: 1,
                    );
                  },
                  itemCount: dataList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ])),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: new Container(
        color: Colors.white,
        padding: EdgeInsets.all(15.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Text(
                    dataList[index].action_zh,
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-3),
                        color: Colors.black),
                  ),
                ),
                Container(width: ScreenUtil.getInstance().setHeight(DP_50)),
                Text(
                  dataList[index].action_symbol + dataList[index].point,
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-3),
                      color: Colors.black87),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(DP_10), 0, 0),
              child: Text(
                dataList[index].create_time,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-4),
                    color: Colors.black54),
              ),
            ),
          ],
        ),
      ),
      onTap: () {},
    );
  }
}
